import axios from 'axios'
import { message } from 'ant-design-vue';
import store from '../store'
import storage from '@/utils/storage';
// axios.defaults.baseURL = 'http://localhost:9090/'
axios.defaults.baseURL = 'http://2i5o874480.qicp.vip'

// 当前正在请求的数量
let requestCount = 0

function showLoading() {
  if (requestCount === 0) {
    store.commit('setHttpLoading', true)
  }
  requestCount++
}

function hideLoading() {
  requestCount--
  if (requestCount === 0) {
    store.commit('setHttpLoading', false)
  }
}

axios.interceptors.request.use(req => {
  console.log('进入请求拦截器', req);
  if (req.loading !== false) {
    showLoading()
  }
  return req
}, err => {
  return Promise.reject(err)
})

axios.interceptors.response.use(res => {

  if (res.config.loading !== false) {
    hideLoading()
  }
  console.log('进入响应拦截器', res);
  if (res.data.code === 200 || (res.data.data && res.data.data.code === 200)) {
    return res.data.data || res.data.result || res.data
  } else {
    message.error(res.message || (res.data && res.data.message) || '未知错误');
    return res
  }
}, err => {
  let str = err.response.message || err.response.data ? err.response.data.message : '网络异常'
  message.error(str);
  return Promise.reject(err)
})

export function POST(url, params, config = { loading: true }) {
  let users = storage.get("users") || {};
  console.log('判断有无user', users);
  if (users && users.cookie) {
    params.cookie = users.cookie
  }

  return new Promise((reslove, reject) => {
    axios.post(url, params, config).then(res => {
      reslove(res)
    }).catch(err => {
      reject(err)
    })
  })
}

export function GET(url, params, loading = true) {
  return new Promise((reslove, reject) => {
    axios.get(url, {
      params,
      loading
    }).then(res => {
      reslove(res)
    }).catch(err => {
      reject(err)
    })
  })
}